<template>
  <view class="page">
    <!--		自习室里当前正在学习的人数-->
    <view class="study-room-user-num-container d-flex justify-end" v-if="details">
      <view class="content d-flex align-center justify-center">{{ `有${details.peopleNumber}位小伙伴正在自习` }}</view>
    </view>

    <view class="form">
      <view class="form-item" v-if="details.studyGoal">
        <view class="label">
          <image class="icon" :src="targetIcon"></image>
          <view class="text">本次学习目标：</view>
        </view>
        <view class="value">{{ details.studyGoal }}</view>
      </view>

      <view class="form-item">
        <view class="label">
          <image class="icon" :src="calendarIcon"></image>
          <view class="text">本次学习计划：</view>
        </view>
        <view class="value">{{ details.studyPlan }}</view>
      </view>

      <view class="form-item">
        <view class="label">
          <image class="icon" :src="clockIcon"></image>
          <view class="text">本次学习时长：</view>
        </view>
        <image :src="getShowNginxPicUrl('3mZHcPJQGaaTeRZBDjrY.png')" class="icon"></image>
        <!--				目标总时长-->
        <view class="target-duration">目标总时长：{{ `${targetDurationObj.h} h ${targetDurationObj.m} min` }}</view>
        <!--				剩余时间-->
        <view class="remain-time d-flex align-center flex-column">
          <!--					还未到计划时间-->
          <template v-if="details && details.targetDuration - currentStudyTime > 0">
            <view class="label">距离完成目标还有</view>
            <text class="time">{{
              `${numberUtils.padZero(remainDurationObj.h)} : ${numberUtils.padZero(remainDurationObj.m)} : ${numberUtils.padZero(
                remainDurationObj.s,
              )}`
            }}</text>
          </template>
          <!--					已经到了计划时间-->
          <view class="label" style="font-weight: bold" v-else>学习任务已完成</view>
        </view>
      </view>

      <!--			追加学习图片-->
      <view class="form-item" v-if="isStudying">
        <view class="label">
          <image class="icon" :src="bookIcon"></image>
          <view class="text">本次学习情况（选填）：</view>
        </view>

        <studyImagesUpload :details="details" ref="studyImagesUpload"></studyImagesUpload>
      </view>
    </view>
    <!--		开始学习按钮-->
    <view class="begin-study-btn d-flex align-center justify-center btn" @click="beginStudy" v-if="!isStudying">开始计时</view>
    <template v-else>
      <!--			结束学习-->
      <view class="break-off-study-btn d-flex align-center justify-center btn" @click="endStudy">结束学习</view>
      <!--			前往学习-->
      <view class="begin-study-btn d-flex align-center justify-center btn" @click="goToStudy">前往学习</view>
    </template>
    <text class="tips">提示：你可以随时离开该页面去进行学习，\n学习时长将持续记录</text>

    <!--		自习报告（自习结束的时候弹出）-->
    <studyReport ref="studyReport" :details="details" v-if="details" :currentStudyTime="currentStudyTime"></studyReport>
  </view>
</template>

<script>
import targetIcon from "./assets/target.png"
import calendarIcon from "./assets/calendar.png"
import clockIcon from "./assets/clock.png"
import dateUtils from "@/utils/dateUtils"
import numberUtils from "@/utils/numberUtils"
import { getEnv, getShowNginxPicUrl } from "@/utils/settings"
import request from "@/utils/request"
import bookIcon from "./assets/book.png"
import store from "@/store"
import { appActionType } from "@/store/modules/app"
import { showModal } from "@/utils"
import studyImagesUpload from "./components/studyImagesUpload.vue"
import studyReport from "./components/studyReport.vue"

let firstOpenPage = true
export default {
  components: { studyImagesUpload, studyReport },
  methods: {
    getShowNginxPicUrl,
    //开始学习
    beginStudy() {
      //记录开始学习时间点
      request({
        url: "studyRoomUserPlan/startStudying",
        data: {
          userPlanId: this.details.userPlanId,
        },
        showLoading: true,
        errorHandle: true,
      }).then(() => {
        this.isStudying = true
        //开启计时器
        this.startCountDown()
      })
    },
    //开启倒计时，计算当前学习时长
    startCountDown() {
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.timer = setInterval(() => {
        this.currentStudyTime = this.currentStudyTime + 1
      }, 1000)
    },
    init() {
      //回显学习状态
      if (this.details.studyStatus === "Studying") {
        this.isStudying = true
        this.currentStudyTime = this.details.studyDuration
        this.startCountDown()
      }
    },
    //结束学习
    async endStudy() {
      if (this.$refs.studyImagesUpload.hasUnsavedChanges) {
        if (
          !(await showModal({
            title: "提示",
            content: "你有未提交的学习情况图片，请先提交更改",
            confirmText: "放弃更改",
            cancelText: "我知道了",
          }))
        )
          return
      }
      if (
        !(await showModal({
          title: "提示",
          content: "确定要结束学习吗？",
        }))
      )
        return
      request({
        url: "studyRoomUserPlan/finishedStudying",
        data: {
          userPlanId: this.details.userPlanId,
        },
        showLoading: true,
        errorHandle: true,
      }).then(() => {
        this.isStudying = false
        //清除计时器
        clearInterval(this.timer)
				//弹出自习报告
				this.$refs.studyReport.open()
      })
    },
    //前往学习
    goToStudy() {
      showModal({
        title: "提示",
        content: "学习完毕后，记得回来记录学习成果哦",
        confirmText: "我知道了",
        showCancel: false,
      }).then(() => {
        uni.reLaunch({ url: "/pages/index/index" })
      })
    },
    //获取计划详情
    async getPlanDetails() {
      this.details = (
        await request({
          url: "studyRoom/allowEntryJoinStudy",
          data: {
            studyRoomId: this.studyRoomId,
          },
          showLoading: true,
          errorHandle: true,
        })
      ).resultData
    },
  },
  data() {
    return {
      details: {
        targetDuration: 0,
      },
      targetIcon,
      calendarIcon,
      clockIcon,
      bookIcon,
      currentStudyTime: 0, //当前学习时长
      timer: null, //计时器，每秒更新一次当前学习时长
    }
  },
  computed: {
    numberUtils() {
      return numberUtils
    },
    //总学习时长
    targetDurationObj() {
      return dateUtils.formatTimeObject2(this.details.targetDuration)
    },
    //剩余学习时长
    remainDurationObj() {
      const remainDuration = this.details.targetDuration - this.currentStudyTime
      return dateUtils.formatTimeObject2(remainDuration < 0 ? 0 : remainDuration)
    },
    //当前是否处于学习状态
    isStudying: {
      set(val) {
        store.commit(appActionType.mutations.studyRoomStudying, val)
      },
      get() {
        return store.getters[appActionType.getters.studyRoomStudying]
      },
    },
    //缓存的自习室id，便于从背单词、刷题界面跳转回来
    studyRoomId: {
      get() {
        return store.getters[appActionType.getters.studyRoomId]
      },
      set(val) {
        store.commit(appActionType.mutations.studyRoomId, val)
      },
    },
  },
  async onLoad(query) {
    if (query.details) {
      this.details = JSON.parse(decodeURIComponent(query.details))
      this.studyRoomId = this.details.studyRoomId
      console.log(this.details, "this.details")
    } else {
      // 进来时没带参数，读取缓存中的计划id获取计划详情
      await this.getPlanDetails()
    }
    this.init()
  },
  async onShow() {
    //从后台切回来的时候计时器可能已经停掉，需要向服务器拉取最新的学习时间
    if (!firstOpenPage) {
      await this.getPlanDetails()
      this.init()
    }
    firstOpenPage = false
  },
}
</script>

<style lang="scss" scoped>
.page {
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));

  > .study-room-user-num-container {
    padding-top: 30rpx;
    padding-right: 30rpx;

    > .content {
      color: #8f5100;
      background: #fff4cc;
      border: 2rpx solid #ffad33;
      border-radius: 52rpx 52rpx 52rpx 52rpx;
      font-size: 30rpx;
      padding: 10rpx 60rpx;
    }
  }

  > .form {
    padding: 30rpx;

    > .form-item {
      width: 100%;
      &:not(:first-child) {
        margin-top: 60rpx;
      }

      > .label {
        display: flex;
        align-items: center;

        .icon {
          width: 46rpx;
          height: 46rpx;
        }

        .text {
          font-size: 34rpx;
          margin-left: 14rpx;
        }
      }

      > .icon {
        margin: {
          top: 30rpx;
          left: auto;
          right: auto;
        }
        width: 491.2rpx;
        height: 281.6rpx;
        display: block;
      }

      > .value {
        font-size: 30rpx;
        margin-top: 20rpx;
        padding: 20rpx;
        //border-radius: 8rpx 8rpx 8rpx 8rpx;
        //border: 2rpx solid #2cb980;
      }

      > .target-duration {
        margin-top: 6rpx;
        text-align: right;
        color: var(--text-color-light);
        font-size: 30rpx;
      }

      > .remain-time {
        margin-top: 46rpx;
        > .label {
          font-size: 36rpx;
          font-weight: 500;
        }
        > .time {
          margin-top: 20rpx;
          color: #2cb980;
          font-size: 60rpx;
          font-weight: bold;
        }
      }

      > .total-time {
        color: var(--text-color-light);
        font-size: 30rpx;
        margin-top: 20rpx;
      }
    }
  }

  > .begin-study-btn {
    background: #2cb980;
  }

  > .btn {
    margin: {
      top: 40rpx;
      left: auto;
      right: auto;
    }
    width: 430rpx;
    height: 80rpx;
    font-size: 32rpx;
    color: white;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
  }

  > .break-off-study-btn {
    background: #ffb200;
  }

  > .tips {
    display: inline-block;
    width: 100%;
    line-height: 1.8;
    text-align: center;
    font-size: 30rpx;
    color: var(--text-color-light);
    margin-top: 30rpx;
  }
}
</style>
